if (window.self === window.top) {
    console.log('添加自定义按钮');
  
    document.onreadystatechange = () => {
          if (document.readyState === 'complete') {
            $("body").append('<div id="dbButton" style="inset: 0px 0px auto auto !important;position: fixed !important;z-index: 2147483647 !important;padding-right: 47px;margin-top: 66px;display: none;"><p id="butPro" style="color:white;margin: 0;">生产：<button id="order" style="color:red;">order</button><button id="bhjh" style="color:red;">bhjh</button><button id="check" style="color:red;">check</button></p><p id="butDev" style="color:white;margin: 0;">沙箱：<button id="order1">order</button><button id="bhjh1" >bhjh</button><button id="check1">check</button></p></div>');
            $("body").append('<div id="logButton" style="inset: 0px 0px auto auto !important;position: fixed !important;z-index: 2147483647 !important;padding-right: 47px;margin-top: 116px;display: none;"><p style="color:white;margin: 0;"><button id="watchLog" >跟踪最新日志</button></p></div>');

            $("#order").click(function(){dbSwitch(1);});
            $("#bhjh").click(function(){dbSwitch(2);});
            $("#check").click(function(){dbSwitch(3);});

            $("#order1").click(function(){dbSwitch(4);});
            $("#bhjh1").click(function(){dbSwitch(5);});
            $("#check1").click(function(){dbSwitch(6);});

            $("#watchLog").click(function(){watchLog();});
            console.log(sessionStorage.getItem("dbSwitch"));
            
            if(sessionStorage.getItem("dbSwitch")=='true' && document.location.href.indexOf('/web/cmd/index.html')>-1){
                sessionStorage.setItem('dbSwitch','false');
                $("#dbButton").show();
            }else if(document.location.href.indexOf('/web/cmd/index.html')>-1){
                $("#logButton").show();
            }
          }
    }
  }
  
  setTimeout(() => {
    console.log("check env");
    let ele = document.querySelector('#root > div > div.App-header > div:nth-child(1)');
    if(!ele){
        return;
    }
    let title = ele.innerText;
    title = title.substring(title.indexOf('/')+1);
    title = title.substring(0,title.indexOf('  '));
    console.log(title);
    if(title && title!=''){
        if(title.startsWith('centos-batch')){
            document.getElementById('dbButton').style.display='block';
        }
        let namespace = GetQueryString('namespace');
        let env = namespace=='1275227919127928834'?'dev':'pro';
        if(env=='pro'){
            console.log('生产环境');
            document.getElementById('butDev').style.display="none";
            var span = document.createElement('span');
            span.innerText = ' 生产环境';
            span.style.color = 'red';
            document.querySelector('#root > div > div.App-header > div:nth-child(1)').appendChild(span);
            document.title='生产 ' + title;
        }else if(env=='dev'){
            console.log('沙箱环境');
            document.getElementById('butPro').style.display="none";
            var span = document.createElement('span');
            span.innerText = ' 沙箱环境';
            span.style.color = 'green';
            document.querySelector('#root > div > div.App-header > div:nth-child(1)').appendChild(span);
            document.title='沙箱 ' + title;
        }else{

        }
    }
  }, 2000);

//   $(document).on('click', 'a', function(event) {
//     if(event.target.innerText=='终端'){
//         let env = parseEnv();
//         if(!env || env==''){
//             return;
//         }
//         const spanArray = document.getElementsByTagName('a');
//         for(let item of spanArray){
//             let dz = item['title'];
//             if(dz.startsWith('centos-batch') 
//                 || dz.startsWith('yh') 
//                 || dz.startsWith('bhjh')
//                 || dz.startsWith('onlinestore')){
//                 sessionStorage.setItem(dz, env);
//             }
//         }
//     }
//   });

  function parseEnv(){
    let env = document.querySelector("#root-master > div > section > aside > div > div > div > div > div > div > div.slick-slide.slick-active.slick-current > div > div > div > span:nth-child(2)").innerText;
    if('生产域运维'==env){
        env = 'pro';
    }else if('测试域运维'==env){
        env = 'dev';
    }
    return env;
  }

  let connectArrayPro = [' mysql -h mysql-1268346182313312258-0085m.k19029219 -P 3308 -u cmscro -D onlinestore_order -pcmscro@Cmsc2019 ',
                        ' mysql -h mysql-1268346182313312258-0085m.k19029219 -P 3308 -u cmscro -D bhjh -pcmscro@Cmsc2019 -A',
                        ' mysql -h mysql-1268346182313312258-0085m.k19029219 -P 3308 -u cmscro -D onlinestore_check -pcmscro@Cmsc2019 -A'];
  let connectArrayDev = [' mysql -h 10.253.148.250 -u cmscsandbox -D onlinestore_order -pcmscsandbox@Cmsc2019 -A',
                        ' mysql -h 10.253.148.250 -u cmscsandbox -D bhjh -pcmscsandbox@Cmsc2019 -A',
                        ' mysql -h 10.253.148.250 -u cmscsandbox -D onlinestore_check -pcmscsandbox@Cmsc2019 -A'];
  let runningConnectSt = '';
  let intervalAutoInput = {};

  function dbSwitch(type){
    console.log("切换数据库" + type);
  
    var objInput = document.getElementsByClassName("xterm-helper-textarea")[0];

    let index = 0;
    let quit = "quit";
    let indexQuit = 0;
    if(type<=3){ // 生产
        runningConnectSt = connectArrayPro[type-1];
    }else{ // 沙箱
        runningConnectSt = connectArrayDev[type-4];
    }

    intervalAutoInput = setInterval(function(){
        if(indexQuit <= quit.length){
            if(indexQuit != quit.length){
                dispatchEventCustum2(objInput, quit[indexQuit]);
            }
            if(indexQuit == quit.length){
                enterEvent(objInput);
            }
            indexQuit++;
        }else{
            dispatchEventCustum2(objInput, runningConnectSt[index]);
            if(index == runningConnectSt.length-1){
                console.log('finished');
                enterEvent(objInput);
                index = 0;
                clearInterval(intervalAutoInput);
            }
            index++;
        }
    }, 40);
  }
  
  function watchLog(){
    let intervalAutoInput = {};
    let indexQuit = 0;
    let appPodName = GetQueryString('podName');
    if(!appPodName || appPodName==''){
        appPodName = getAppPodNameFromHtmlHead();
    }
    console.log('app Name :' + appPodName);
    if(!appPodName || appPodName==''){
        console.error('未获取到app名称')
        return;
    }
    let h4 = appPodName.split('-');
    if(!h4 || h4.length<2){
        console.error('app名称解析错误')
        return;
    }
    let rowApp = h4[0] + "-" + h4[1];
    console.log("app :" + rowApp);
    var date = new Date();
    let month = date.getMonth() + 1;
    if(month < 10){
        month = "0" + month;
    }
    let day = date.getDate();
    if(day < 10){
        day = "0" + day;
    }

    let index = 0;
    let cmd = 'cd ~/'+rowApp + '/logs/' + date.getFullYear() + "-" + month + "/" + day + '/';
    console.log('run:' + cmd);
    let hour = date.getHours();
    if(hour<10){
        hour = "0" + hour;
    }
    let cmd2 = 'tail -f application.' + date.getFullYear() + "-" + month + "-" + day
    + '-' + hour
    + '.' + h4[0] + "-" + h4[1] + '-' + h4[2] + "*log";
    console.log('run2:' + cmd2);

    var objInput = document.getElementsByClassName("xterm-helper-textarea")[0];
    let rf = false;
    intervalAutoInput = setInterval(function(){
        if(index == -2){
            clearInterval(intervalAutoInput);
            return;
        }
        if((index == 0 || index>=cmd.length) && !rf){
            enterEvent(objInput);
        }
        if(index<=cmd.length && !rf){
            dispatchEventCustum2(objInput, cmd[index]);
            index++;
            if(index > cmd.length){
                rf = true;
                index = 0;
            }
        }else if(rf){
            if(index <= cmd2.length){
                dispatchEventCustum2(objInput, cmd2[index]);
                index++;
            }else{
                enterEvent(objInput);
                index = -2;
                clearInterval(intervalAutoInput);
            }
        }
    }, 40);
  }

  function resetAutoInput(){
    clearInterval(intervalAutoInput);
  }
  
  function enterEvent(inpEle){
    let kEvent = new KeyboardEvent("keydown", {
        key: 'Enter',
        code: 'Enter',
        keyCode: 13,
        which: 13
    });
    inpEle.dispatchEvent(kEvent)
  }

  let clickServiceName = '';
  $(document).on('click', 'a', function(event) {
    let butName = event?.target?.firstChild?.data;
    if("终端"!=butName){
      clickServiceName = butName;
      // localStorage.setItem('K8SName', event?.target?.firstChild?.data);
    }
  });
  
  // 点击打开控制台
  $(document).on('click', 'a', function(event) {
    // let K8SName = localStorage.getItem("K8SName");
    if('centos-batch' == clickServiceName){
      console.log("开启数据库切换按钮");
      sessionStorage.setItem('dbSwitch','true');
    }else{
        sessionStorage.setItem('dbSwitch','false');
    }
  });
  
  // 点击关闭控制台
  $(document).on('click', 'span[aria-label="close"]', function(event) {
    $("#dbButton").hide();
    resetAutoInput();
  });
  
  
  function dispatchEventCustum2(that, code){
    logInfo('input code:'+code);
    let keyboardEvent = document.createEvent("KeyboardEvent");
    let initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ?"initKeyboardEvent" :"initKeyEvent";
    let keyCode= 48 + code;
  
    keyboardEvent[initMethod](
    "keydown", // event type: keydown, keyup, keypress
    true,      // bubbles
    true,      // cancelable
    window,    // view: should be window
    false,     // ctrlKey
    false,     // altKey
    false,     // shiftKey
    false,     // metaKey
    keyCode,        // keyCode: unsigned long - the virtual key code, else 0
    code          // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
    );
    that.dispatchEvent(keyboardEvent);
  
    let evt = new InputEvent('input', {
        inputType: 'insertText',
        data: code,
        dataTransfer: null,
        isComposing: false
    });
    that.value = code;
    that.dispatchEvent(evt);
  }
  

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = decodeURIComponent(r[2]);
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}

function getAppPodNameFromHtmlHead(){
    let headerInfo = $(".App-header").textContent;
    if(!headerInfo){
        return '';
    }
    let hs = headerInfo.splt('/');
    if(hs.length<2){
        return '';
    }
    let h3 = hs[1].split('  ');
    if(h3.length<3){
        return '';
    }
    return h3[0];
}